package cn.tnar.parkservice.service.impl;

import cn.tnar.parkservice.config.Constant;
import cn.tnar.parkservice.config.ExceptionConst;
import cn.tnar.parkservice.exception.CustomException;
import cn.tnar.parkservice.mapper.TParkOrderMapper;
import cn.tnar.parkservice.model.response.PageResponse;
import cn.tnar.parkservice.model.response.TOrderResponse;
import cn.tnar.parkservice.service.KesbApiService;
import cn.tnar.parkservice.service.TParkOrderService;
import cn.tnar.parkservice.util.DateUtil1;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import cn.tnar.parkservice.util.common.StringUtil;
import cn.tnar.pms.kesb.KesbException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: xinZhang
 * @Date: 2019/9/3
 * @Description:
 */
@Service
@Slf4j
public class TParkOrderServiceImpl implements TParkOrderService {

    @Autowired
    private TParkOrderMapper orderMapper;

    @Autowired
    private KesbApiService kesbApiService;

    private static final String NORMAL_ORDER_STATUS = "1";

    /**
     * 当日停车流水，历史停车流水列表查询
     * 参数queryFlag查询当日，历史流水区别标识
     * @param request
     * @return
     */
    @Override
    public ResultJson getParkRecord(Map<String,Object> request) {
        Page<Map<String,String>> page = null;
        try {
            Integer pageSize = (Integer) request.get("pageSize");
            Integer pageNo =(Integer) request.get("pageNo");
            //查询当日：true  查询历史：false
            Boolean queryFlag =(Boolean) request.get("queryFlag");
            page = new Page<>(pageNo, pageSize);
            String park_code = (String)request.get("park_code");
            if (StringUtil.isBlank(park_code)){
                throw new CustomException(ExceptionConst.PARAM_PARK_CODE_NOT_NULL);
            }
            List<Map<String,String>> list = null;
            if (queryFlag){
                list = orderMapper.getDailyParkRecord(page,request);
            }else {
                list = orderMapper.getHisParkRecord(page,request);
            }
            page.setRecords(list);
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(page);
        } catch (CustomException e) {
            e.printStackTrace();
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }

    }


    /**
     * 查询停车中流水
     * @param request
     * @return
     */
    @Override
    public ResultJson getParkingRecord(Map<String, Object> request) {
        try {
            Integer pageSize = (Integer) request.get("pageSize");
            Integer pageNo =(Integer) request.get("pageNo");
            Page<Map<String,Object>> page = new Page<>(pageNo, pageSize);
            List<Map<String, Object>> list = orderMapper.getParkingRecord(page, request);
            list.forEach(map ->{
                String intime = map.get("intime").toString();
                String totalTime = getTime(intime);
                map.put("totalTime",totalTime);
            });
            page.setRecords(list);
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(page);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }

    /**
     * 计算时长
     * @param time 车辆入场时间
     * @return xx小时xx分钟
     */
    private String getTime(String time){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHssmm");
        int nh = 1000*60*60;
        int nm = 1000*60;
        try {
            Date intime = sdf.parse(time);
            Long count = new Date().getTime() - intime.getTime();
            long hh = count / nh;
            long mm = count % nh / nm;
            return hh+"小时"+mm+"分";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询订单
     * @param
     * @return
     */
    @Override
    public ResultJson queryOrder(Map<String,String> request) {
        int pageNo = Integer.parseInt(request.get("pageNo"));
        int pageSize = Integer.parseInt(request.get("pageSize"));
        Boolean queryFlag = Boolean.valueOf(request.get("queryFlag"));

        List<TOrderResponse> response = new ArrayList<>();
        if (queryFlag){
            response = orderMapper.queryDayOrder(request);
        }else {
            response = orderMapper.queryHisOrder(request);
        }
        PageResponse page = getPage(pageNo, pageSize, response);
        BigDecimal etcAamount = new BigDecimal("0.00") ;
        int etcRecord = 0;
        BigDecimal jhAmount = new BigDecimal("0.00");
        int jhRecord = 0;
        BigDecimal wxAmount = new BigDecimal("0.00");
        int wxRecord = 0 ;
        BigDecimal zfbAmount = new BigDecimal("0.00");
        int zfbRecord = 0 ;
        BigDecimal cxcAmount = new BigDecimal("0.00");
        int cxcRecord = 0 ;
        //统计金额
        for (TOrderResponse tOrderResponse : response) {
            if (tOrderResponse.getPayType() == 1){
                //微信
                wxAmount=wxAmount.add(tOrderResponse.getTradeamount());
                wxRecord++;
            }
            if (tOrderResponse.getPayType() == 2){
                //支付宝
                zfbAmount=zfbAmount.add(tOrderResponse.getTradeamount());
                zfbRecord++;
            }
            if (tOrderResponse.getPayType() == 10){
                //聚合支付
                jhAmount=jhAmount.add(tOrderResponse.getTradeamount());
                jhRecord++;
            }
            if (tOrderResponse.getPayType() == 24){
                //ETC支付
                etcAamount=etcAamount.add(tOrderResponse.getTradeamount());
                etcRecord++;
            }
            if (tOrderResponse.getPayType() == 26){
                //畅行车
                cxcAmount=cxcAmount.add(tOrderResponse.getTradeamount());
                cxcRecord++;
            }
        }
        Map<String, Object> total = orderMapper.getAccount(request);
        HashMap<String, Object> account = new HashMap<>();
        account.put("total_jh_amount",jhAmount);
        account.put("total_jh_record",jhRecord);
        account.put("total_wx_amount",wxAmount);
        account.put("total_wx_record",wxRecord);
        account.put("total_zfb_amount",zfbAmount);
        account.put("total_zfb_record",zfbRecord);
        account.put("total_etc_amount",etcAamount);
        account.put("total_etc_record",etcRecord);
        account.put("total_cxc_amount",cxcAmount);
        account.put("total_cxc_record",cxcRecord);
        account.put("total",total);
        HashMap<String, Object> resp = new HashMap<>();
        resp.put("page",page);
        resp.put("account",account);
        return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(resp);
    }
    private PageResponse getPage(Integer pageNoInt, Integer pageSizeInt, List<TOrderResponse> list) {
        PageResponse page = new PageResponse();
        //刚开始的页面为第一页
        if (page.getCurrent() == null) {
            page.setCurrent(1);
        } else {
            page.setCurrent(pageNoInt);
        }
        //设置每页数据条数
        page.setSize(pageSizeInt);
        //每页的开始记录数
        page.setStar((pageNoInt - 1) * (page.getSize()));
        //数据集合大小
        int count = list.size();
        //设置总记录数
        page.setTotal(Long.valueOf(String.valueOf(count)));
        //设置总页数
        page.setPages(count % pageSizeInt == 0 ? count / pageSizeInt : count / pageSizeInt + 1);
        //对list进行截取
        Integer formIndex = page.getStar();
        Integer tolIndex = count - page.getStar() > page.getSize() ? page.getStar() + pageSizeInt : count;
        //排序
        page.setRecords(list.subList(formIndex, tolIndex));
        return page;
    }
}
